package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.mapper.ApBehaviorEntryMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP行为实体表,一个行为实体可能是用户或者设备，或者其它 服务实现类
 * </p>
 *
 * @author syl
 * @since 2022-02-16
 */
@Service
public class ApBehaviorEntryServiceImpl extends ServiceImpl<ApBehaviorEntryMapper, ApBehaviorEntry> implements IApBehaviorEntryService {

    @Override
    public ApBehaviorEntry getEntryByUserIdOrEquipmentId(FollowBehaviorDto followBehaviorDto) {
//        实体有可能存在 也有可能不存在  如果不存在 需要新增
        if (followBehaviorDto.getUserId()==0) { //未登录，根据设备id
//            followBehaviorDto.getEquipmentId()
//            }
            LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
             queryWrapper.eq(ApBehaviorEntry::getEntryId, followBehaviorDto.getEquipmentId());
            ApBehaviorEntry behaviorEntry = this.getOne(queryWrapper);
            if(behaviorEntry==null){
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType(0); //0代表的是设备
                behaviorEntry.setEntryId(followBehaviorDto.getEquipmentId());
                behaviorEntry.setCreatedTime(new Date());
                this.save(behaviorEntry);
            }
            return behaviorEntry;
        }else{
            LambdaQueryWrapper<ApBehaviorEntry> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ApBehaviorEntry::getEntryId, followBehaviorDto.getUserId());
            ApBehaviorEntry behaviorEntry = this.getOne(queryWrapper);
            if(behaviorEntry==null){
                behaviorEntry = new ApBehaviorEntry();
                behaviorEntry.setType(1); //0代表的是用户id
                behaviorEntry.setEntryId(followBehaviorDto.getUserId().toString());
                behaviorEntry.setCreatedTime(new Date());
                this.save(behaviorEntry);
            }
            return behaviorEntry;
        }
    }
}
